<?php

use Phalcon\Di\FactoryDefault;
use Phalcon\Mvc\Application;

define('BASE_PATH', dirname(__DIR__));
define('APP_PATH', BASE_PATH . '/app');

//网址忽略大小写
//if (isset($_GET['_url'])) {
//    $_GET['_url'] = strtolower($_GET['_url']);
//}

// 自定义异常处理函数
set_exception_handler('exception_handler');


    /**
     * The FactoryDefault Dependency Injector automatically registers the services that
     * provide a full stack framework. These default services can be overidden with custom ones.
     */
    $di = new FactoryDefault();

    /**
     * Include general services
     */
    require APP_PATH . '/config/services.php';

    /**
     * Include web environment specific services
     */
    require APP_PATH . '/config/services_web.php';

    /**
     * Get config service for use in inline setup below
     */
    $config = $di->getConfig();

    /**
     * Include Autoloader
     */
    include APP_PATH . '/config/loader.php';

    /**
     * Handle the request
     */
    $application = new Application($di);

    /**
     * Register application modules
     */
    $modulesConfig = include APP_PATH . "/config/modules.php";
    $application->registerModules($modulesConfig);

    /**
     * Include routes
     */
    require APP_PATH . '/config/routes.php';

    /**
     * Include Composer autoload
     */
    require_once '../vendor/autoload.php';

    /**
     * Check Debug
     */
//    if (!\Helpers\Debug::isEnable()) {
//        echo $application->handle()->getContent();
//    } else {
//        \Helpers\Debug::doStart();
//    }

$debug     = $application->session->get('DEBUG', []);
$debugMode = \Helpers\Tool::getValue($debug, 'mode', '');
if ($debugMode == 'debugbar') {
    $di['app'] = $application;
    $provider  = new Snowair\Debugbar\ServiceProvider(APP_PATH . '/config/debugbar.php');
    $provider->register();
    $provider->boot();
    \PhalconDebug::startMeasure('content');
    \PhalconDebug::addMeasurePoint('handle');
    echo $application->handle()->getContent();
    \PhalconDebug::stopMeasure('content');
} elseif ($debugMode == 'xhprof') {
    xhprof_enable(XHPROF_FLAGS_MEMORY, ['ignored_functions' => [
        'Closure::{closure}',
        'Composer\Autoload\ClassLoader::loadClass',
        'Composer\Autoload\ClassLoader::findFile',
        'Helpers\Controller::onConstruct',
        'load::utils/xhprof_lib.php',
        'load::utils/xhprof_runs.php'
    ]]);
    echo $application->handle()->getContent();
    $xhprof_path = '../public/xhprof/xhprof_lib/utils/';
    if (file_exists($xhprof_path . 'xhprof_lib.php') && file_exists($xhprof_path . 'xhprof_runs.php')) {
        require_once $xhprof_path . 'xhprof_lib.php';
        require_once $xhprof_path . 'xhprof_runs.php';
        $xhprof_data = xhprof_disable();
        $xhprof_runs = new XHProfRuns_Default();
        $run_id      = $xhprof_runs->save_run($xhprof_data, 'xh_admin');
    }
} else {
    echo $application->handle()->getContent();
}

/**
 * 异常处理函数
 *
 * @param \Throwable|\Exception|\Error $exception
 *
 * create by ck 20190220
 */
function exception_handler($exception)
{
    $_code = strlen($exception->getCode()) === 3 ? $exception->getCode() : 500;
    $_detail = $exception->getTrace();
    if ($exception instanceof \Helpers\Exception\BaseException) {
        $_detail = $exception->getDescription();
    }
    if ($exception instanceof \Helpers\XhException) {
        $_detail = $exception->getDescription();
    }

    if (\Helpers\Di::get()->db->isUnderTransaction()) {
        \Helpers\Di::get()->db->rollback();
    }

    ob_clean();
    $controller = new \Helpers\Controller();
    header('HTTP/1.0 ' . ($exception->getCode() ?: 500));
    header('Content-Type: application/json');
    echo $controller->sendErrorResponse(
        $_code,
        $exception->getMessage(),
        $_detail
    )->getContent();
}
